import { useEffect } from 'react';
import {
  Outlet, // Navigate,
  RouteObject,
  createHashRouter,
  useLocation,
  useNavigate
} from 'react-router-dom';

import { lazyLoad } from '@/components/loadable';

import { layoutStore } from '@/store/layout';
// import { getBaseRedirect, getRedirectPath } from "@/store/layout/utils";
import { getBaseRedirect, getRedirectPath, getSubMenuKey } from '@/store/layout/utils';

import { checkPermission } from '@/auth';

import { adminRouter, commonRouter } from '../routes/router.config';
import { formatRoutes } from '../routes/utils';

export const commonRouterConfig = formatRoutes(commonRouter);

// const removeRouteArray = ['monitoring', 'pid', 'report'];
// const routerFormat = (routes: RouteObject[], paths: string[]) => {
//   //判断是移动端还是PC端
//   const isMobile = /mobile/i.test(navigator.userAgent);
//   console.log('isMobile', isMobile);

//   const pathSet = new Set(paths);

//   function processArray(arr: any[]) {
//     for (let i = arr.length - 1; i >= 0; i--) {
//       const item = arr[i];

//       // 如果当前对象的path在要删除的列表中
//       if (item.path && pathSet.has(item.path)) {
//         // 从数组中删除该对象
//         arr.splice(i, 1);
//         continue; // 删除后继续处理下一个
//       }

//       // 如果当前对象有children且是数组，递归处理children
//       if (item.children && Array.isArray(item.children)) {
//         processArray(item.children);

//         // 如果处理后的children为空，可以选择是否删除该对象
//         if (item.children.length === 0) {
//           // 可选：删除空的children属性
//           delete item.children;
//         }
//       }
//     }
//   }

//   if (isMobile) {
//     processArray(routes);
//   }

//   return routes;
// };

// export const adminRouterConfig = formatRoutes(
//   routerFormat(adminRouter as RouteObject[], removeRouteArray) as any
// );

export const adminRouterConfig = formatRoutes(adminRouter);

export const routerConfig: RouteObject[] = [
  {
    element: <Redirect />,
    children: [
      {
        element: lazyLoad(() => import('@/layouts/basic'), undefined),
        children: [...adminRouterConfig]
      },
      ...commonRouterConfig
    ]
  }
] as RouteObject[];

function Redirect() {
  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    const redirectPath = getRedirectPath(routerConfig);
    const baseRedirect = getBaseRedirect(routerConfig, []);

    if (baseRedirect) {
      redirectPath.unshift({
        from: '/',
        to: baseRedirect
      });
    }

    const currentPath = location.pathname;
    const redirect = redirectPath.find((config) => {
      return config.from === currentPath;
    });

    if (redirect) {
      navigate(redirect.to, {
        replace: true
      });
    } else {
      //处理当前路由无权限访问时，跳转到下一个有权限的路由
      if (!checkPermission(`admin:${currentPath}`)) {
        const subMenu = layoutStore.subMenu;
        const path = getSubMenuKey(subMenu);
        console.log('path:', path);
        if (path) {
          navigate(path, {
            replace: true
          });
        }
      }
    }
  }, [location.pathname, navigate]);

  return (
    <>
      <Outlet />
    </>
  );
}

// console.log(routerConfig)
export const router: ReturnType<typeof createHashRouter> = createHashRouter(routerConfig);
